#
# Message class
#
package Mail::Bounce;

use strict;

use vars qw($DEBUG @ISA);

$DEBUG = 0;

use MIME::Entity;
use Mail::Bounce::Standard;
use Mail::Bounce::Standard::Buggy;
use Mail::Bounce::Heuristic;

@ISA = qw(MIME::Entity);

sub classify {
    my $self = shift;

    if ($self->is_multipart && $self->mime_type eq "multipart/report") {
	my $rtype = $self->head->mime_attr("content-type.report-type");
	if ("\L$rtype" eq "delivery-status") {
	    $DEBUG && warn "Classifying as Standard\n";
	    bless $self, "Mail::Bounce::Standard";
	    # There are some buggy versions of Sendmail that return
	    # standard reports without any recipients, but return
	    # parseable error reports in the first bodypart. Try.
            eval {
		if ($self->recipients() == 0) {
		    $DEBUG && warn "Seeing if Heuristic helps\n";
		    bless $self, "Mail::Bounce::Standard::Buggy";
 		    Mail::Bounce::Heuristic::classify($self);

		}
	    };
	    # Some errors return via die()...
	    if ($@) {
		if ($@ =~ /Illegal status value /
		    || $@ =~ /ERR: not a message\/delivery-status/
		    || $@ =~ /Erroneous line/
		    || $@ =~ /No action found/) {
		    $DEBUG && warn "Parse failed ($@) - try adhoc\n";
		    bless $self, "Mail::Bounce::Standard::Buggy";
		    Mail::Bounce::Heuristic::classify($self);
		} else {
                    $DEBUG && warn "Standard parse died - passing up\n";
		    die $@; # pass error up
		}
	    }
	}
    } else {
        Mail::Bounce::Heuristic::classify($self);
    }
}

sub isbounce {
# if it hasn't been subclassed, it isn't a bounce
    return 0;
}

sub validate {
# if it hasn't been subclassed, it is a valid class member....
    return 1;
}

sub recipients {
# returns an array of Mail::Bounce::Address elements
    die "recipients() not implemented for this class\n";
}
sub bounce_destination {
# to: address of message - to get at subaddresses and such
    my $self = shift;
    my $to = $self->head->get("to");
    if ($to) {
	chop $to;
	# strip away enclosing angle brackets
	if ($to =~ /<(.*)>/) {
	    $to = $1;
	}
    }
    return $to;
}
sub bounce_origin {
# dns;mta or mail:from
    my $self = shift;
    my $from = $self->head->get("from");
    chop $from;
    return $from;
}

